import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import moment from 'moment';
import { Row, Col, Card, Form, Input, Button, DatePicker, Modal, message, Divider } from 'antd';
import StandardTable from '@/components/StandardTable';
// import DictSelect from '@/components/DictSelect';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import { getAuthorityToken } from '@/utils/authority';
import router from 'umi/router';

import styles from '../List/TableList.less';

const FormItem = Form.Item;
const getValue = obj =>
  Object.keys(obj)
    .map(key => obj[key])
    .join(',');

@connect(({ exampleOrder, dictionary, loading }) => ({
  exampleOrder,
  dictionary,
  loading: loading.models.exampleOrder,
}))
@Form.create()
class ExampleOrderList extends PureComponent {
  state = {
    selectedRows: [],
    formValues: {},
  };

  componentDidMount() {
    const {
      dispatch,
      exampleOrder: {
        data: {
          pagination: { pageSize },
        },
      },
    } = this.props;
    dispatch({
      type: 'exampleOrder/fetch',
      payload: {
        size: pageSize,
      },
    });
  }

  handleStandardTableChange = (pagination, filtersArg, sorter) => {
    const { dispatch } = this.props;
    const { formValues } = this.state;

    const filters = Object.keys(filtersArg).reduce((obj, key) => {
      const newObj = { ...obj };
      newObj[key] = getValue(filtersArg[key]);
      return newObj;
    }, {});

    const params = {
      ...formValues,
      ...filters,
      page: pagination.current - 1,
      size: pagination.pageSize,
    };
    if (sorter.field) {
      params.sorter = `${sorter.field}_${sorter.order}`;
    }

    dispatch({
      type: 'exampleOrder/fetch',
      payload: params,
    });
  };

  handleFormReset = () => {
    const { form } = this.props;
    form.resetFields();
    this.doSearch();
  };

  handleRemove = () => {
    const { dispatch } = this.props;
    const { selectedRows } = this.state;

    if (!selectedRows) return;
    const onOkf = () => {
      dispatch({
        type: 'exampleOrder/remove',
        payload: {
          ids: selectedRows.map(row => row.orderId).join(','),
        },
        callback: () => {
          this.setState({
            selectedRows: [],
          });
          message.info('已成功删除');
          this.doSearch();
        },
      });
    };
    Modal.confirm({
      title: '删除',
      content: '确定永久删除选定的记录吗？',
      okText: '确定删除',
      okType: 'danger',
      cancelText: '取消',
      onOk: onOkf,
      onCancel() {
        // console.log('Cancel');
      },
    });
  };

  handleSelectRows = rows => {
    this.setState({
      selectedRows: rows,
    });
  };

  doSearch = () => {
    const {
      dispatch,
      form,
      exampleOrder: {
        data: {
          pagination: { pageSize },
        },
      },
    } = this.props;

    form.validateFields((err, fieldsValue) => {
      if (err) return;

      const values = {
        size: pageSize,
        ...fieldsValue,
        le_submitTime:
          fieldsValue.le_submitTime && fieldsValue.le_submitTime.format('YYYY-MM-DD HH:mm:ss'),
        ge_submitTime:
          fieldsValue.ge_submitTime && fieldsValue.ge_submitTime.format('YYYY-MM-DD HH:mm:ss'),
      };

      // console.log(values)

      this.setState({
        formValues: values,
      });

      dispatch({
        type: 'exampleOrder/fetch',
        payload: values,
      });
    });
  };

  handleSearch = e => {
    e.preventDefault();

    this.doSearch();
  };

  handleExport = e => {
    e.preventDefault();
    const { form } = this.props;

    form.validateFields((err, fieldsValue) => {
      if (err) return;

      const fvalues = {
        ...fieldsValue,
        le_submitTime:
          fieldsValue.le_submitTime && fieldsValue.le_submitTime.format('YYYY-MM-DD HH:mm:ss'),
        ge_submitTime:
          fieldsValue.ge_submitTime && fieldsValue.ge_submitTime.format('YYYY-MM-DD HH:mm:ss'),
      };

      let params = '';
      // for (const v in fvalues) {
      //   if (fvalues[v] !== null && fvalues[v] !== undefined) {
      //     params += `$d{v}=$d{fvalues[v]}&`;
      //   }
      // }
      Object.entries(fvalues).forEach(item => {
        const key = item[0];
        const value = item[1];
        if (value !== null && value !== undefined) {
          params += `${key}=${value}&`;
        }
      });

      open(`/api/example/order/exampleOrder/export?${params}tokenid=${getAuthorityToken()}`);
    });
  };

  handleImport = () => {
    router.push('/order/exampleOrder/batch');
  };

  handleShow = (e, key) => {
    router.push(`/order/exampleOrder/${key}`);
  };

  handleAdd = () => {
    router.push(`/order/exampleOrder/add/0`);
  };

  handleEdit = (e, key) => {
    router.push(`/order/exampleOrder/edit/${key}`);
  };

  renderAdvancedForm() {
    const { form } = this.props;
    const { getFieldDecorator } = form;
    return (
      <Form onSubmit={this.handleSearch} layout="inline">
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={6} sm={24}>
            <FormItem label="下单用户=">
              {getFieldDecorator('eq_operAccount')(<Input placeholder="请输入" />)}
            </FormItem>
          </Col>
          <Col md={6} sm={24}>
            <FormItem label="下单时间<=">
              {getFieldDecorator('le_submitTime')(
                <DatePicker
                  style={{ width: '100%' }}
                  format="YYYY-MM-DD HH:mm:ss"
                  showTime={{ defaultValue: moment('00:00:00', 'HH:mm:ss') }}
                  placeholder="选择日期"
                />
              )}
            </FormItem>
          </Col>
          <Col md={6} sm={24}>
            <FormItem label="下单时间>=">
              {getFieldDecorator('ge_submitTime')(
                <DatePicker
                  style={{ width: '100%' }}
                  format="YYYY-MM-DD HH:mm:ss"
                  showTime={{ defaultValue: moment('00:00:00', 'HH:mm:ss') }}
                  placeholder="选择日期"
                />
              )}
            </FormItem>
          </Col>
          <Col md={6} sm={24}>
            <FormItem label="订单状态=">
              {getFieldDecorator('eq_orderStatus')(<Input placeholder="请输入" />)}
            </FormItem>
          </Col>
        </Row>
        <div style={{ overflow: 'hidden' }}>
          <span style={{ float: 'right', marginBottom: 24 }}>
            <Button icon="search" type="primary" htmlType="submit">
              查询
            </Button>
            <Button style={{ marginLeft: 8 }} onClick={this.handleFormReset}>
              重置
            </Button>
            <Button icon="export" style={{ marginLeft: 8 }} onClick={this.handleExport}>
              导出
            </Button>
            <Button icon="cloud-download-o" style={{ marginLeft: 8 }} onClick={this.handleImport}>
              导入
            </Button>
          </span>
        </div>
      </Form>
    );
  }

  renderForm() {
    return this.renderAdvancedForm();
  }

  render() {
    const {
      exampleOrder: { data },

      loading,
    } = this.props;
    const { selectedRows } = this.state;

    const columns = [
      {
        title: '订单号',
        dataIndex: 'orderId',
      },
      {
        title: '下单用户',
        dataIndex: 'operAccount',
      },
      {
        title: '下单时间',
        dataIndex: 'submitTime',
      },
      {
        title: '订单总额',
        dataIndex: 'totalPrice',
      },
      {
        title: '收货人名称',
        dataIndex: 'userName',
      },
      {
        title: '收货地址',
        dataIndex: 'userAddress',
      },
      {
        title: '订单状态',
        dataIndex: 'orderStatus',
      },
      {
        title: '操作',
        render: (text, record) => (
          <Fragment>
            <a onClick={e => this.handleEdit(e, record.orderId)}>编辑</a>
            <Divider type="vertical" />
            <a onClick={e => this.handleShow(e, record.orderId)}>查看</a>
          </Fragment>
        ),
      },
    ];

    return (
      <PageHeaderWrapper>
        <Card bordered={false}>
          <div className={styles.tableList}>
            <div className={styles.tableListForm}>{this.renderForm()}</div>
            <div className={styles.tableListOperator}>
              <Button icon="plus" type="primary" onClick={this.handleAdd}>
                新建
              </Button>
              {selectedRows.length > 0 && (
                <span>
                  <Button icon="minus" type="dashed" onClick={this.handleRemove}>
                    删除
                  </Button>
                </span>
              )}
            </div>
            <StandardTable
              selectedRows={selectedRows}
              loading={loading}
              data={data}
              columns={columns}
              onSelectRow={this.handleSelectRows}
              onChange={this.handleStandardTableChange}
              rowKey="orderId"
            />
          </div>
        </Card>
      </PageHeaderWrapper>
    );
  }
}
export default ExampleOrderList;
